package com.data.mall.etl.service.impl;

import com.data.mall.etl.domain.Funnel;
import com.data.mall.etl.domain.FunnelAnalysis;
import com.data.mall.etl.dto.FunnelAnalysisDTO;
import com.data.mall.etl.repository.FunnelAnalysisRepository;
import com.data.mall.etl.repository.FunnelRepository;
import com.data.mall.etl.service.FunnelAnalysisService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @author shixukai
 * @Package com.data.mall.etl.service.impl
 * @Description: TODO
 * @date 2021/5/4
 */
public class FunnelAnalysisServiceImpl implements FunnelAnalysisService {
    @Autowired
    FunnelRepository funnelRepository;
    @Autowired
    FunnelAnalysisRepository funnelAnalysisRepository;

    @Override
    public void save(FunnelAnalysisDTO dto) {
        Funnel funnel = funnelRepository.saveAndFlush(Funnel.builder().funnelName(dto.getFunnelName()).build());
        int i=1;
        for(FunnelAnalysis analysis:dto.getFunnelAnalysisList()){
            funnelAnalysisRepository.save(FunnelAnalysis.builder().funnelId(funnel.getId()).event(analysis.getEvent()).orderSort(i++).build());
        }
    }

    @Override
    public FunnelAnalysisDTO findByFunnelId(Long funnelId) {
        Funnel funnel = funnelRepository.findById(funnelId).get();
        List<FunnelAnalysis> funnelAnalyses = funnelAnalysisRepository.findAllByFunnelIdOrderByOrderSort(funnelId);
        return FunnelAnalysisDTO.builder().funnelName(funnel.getFunnelName()).funnelAnalysisList(funnelAnalyses).build();
    }

    @Override
    public List<FunnelAnalysisDTO> findByFunnelList() {

        List<FunnelAnalysisDTO> funnelAnalysisDTOList = new ArrayList<>();

        List<Funnel> funnels = funnelRepository.findAll();
        for(Funnel funnel:funnels){
            funnelAnalysisDTOList.add(findByFunnelId(funnel.getId()));
        }
        return funnelAnalysisDTOList;
    }
}
